import { FC, useEffect, useRef, useState } from "react";
import { useLocation } from "react-router-dom";
import styles from "./index.module.scss";
import DOMPurify from "dompurify";
import highlight from "highlight.js";
import "highlight.js/styles/github.css";
import ContentLoader from "react-content-loader";
import {
    collectArticle,
    followAuthor,
    getArticleById,
    likeArticle,
    getArticleComments,
    getMoreArticleComments,
} from "@/store/actions/article";
import throttle from "lodash/throttle"; //调用lodash中的节流函数
import Back from "@/shared/back";
import Header from "@/shared/header";
import { MoreOutline } from "antd-mobile-icons";
import dayjs from "dayjs";
import {
    InfiniteScroll,
    Popup,
    Toast,
    NavBar,
    TextArea,
    Button,
} from "antd-mobile";
import Icon from "@/components/icon";
import { FillinOutline } from "antd-mobile-icons";
import { useDispatch, useSelector } from "react-redux";
import Comment from "./components/Comment";
import { http } from "@/utils/http";
import { ArticleCommentResponse } from "@/types/data";

interface ArticleProps { }
// 使用枚举类型来指定评论类型：
enum CommentType {
    Article = "a",
    Comment = "c",
}

// 使用：
//CommentType.Article 表示文章的评论
//CommentType.Comment 表示评论的回复
// 导航栏高度的常量
const NAV_BAR_HEIGTH = 45;
const Article: FC<ArticleProps> = () => {
    const [visible1, setVisible1] = useState(false);
    const dispatch = useDispatch();
    // 关注作者的函数
    const onFollow = (aut_id: any, is_followed: any) => {
        // console.log(aut_id, is_followed);

        dispatch(followAuthor(aut_id, is_followed) as any);
    };

    // 收藏 or 取消收藏 -- 文章
    const onCollected = async (aut_id: any, is_collected: any) => {
        await dispatch(collectArticle(aut_id, is_collected) as any);
        Toast.show(is_collected ? "取消收藏" : "已收藏");
    };
    // 点赞 或 取消点赞 -- 文章
    const onLike = async (art_id: any, attitude: any) => {
        await dispatch(likeArticle(art_id, attitude) as any);
        Toast.show(attitude ? "取消点赞" : "已点赞");
    };

    let [TextAreavalue, setTextAreavalue] = useState("");
    const location = useLocation();
    // console.log(location);
    const pathname = location.pathname;

    // 使用split方法将pathname字符串按'/'分割成数组
    const pathArray = pathname.split("/");

    // 获取文章ID，假设文章ID在数组的最后一个元素
    const artId = pathArray[pathArray.length - 1];
    //拿到准备好的文章、评论数据
    const { detail, comment } = useSelector((state: any) => state.article);
    const [loading, setLoading] = useState(true);
    // 获取文章详情数据
    useEffect(() => {
        localStorage.setItem("artId", artId);
        const loadingData = async () => {
            try {
                await dispatch(getArticleById(artId) as any);
                setLoading(false);
            } catch (error) { }
        };
        loadingData();
    }, [dispatch]);

    // 解构出文章详情数据
    const { content, art_id } = detail ?? {};

    // 文章详情代码内容高亮
    useEffect(() => {
        const dgHtmlDOM = document.querySelector(".dg-html");
        const codes = dgHtmlDOM?.querySelectorAll<HTMLElement>("pre code");

        if (codes && codes.length > 0) {
            codes.forEach((el) => {
                highlight.highlightElement(el);
            });
            return;
        }

        highlight.configure({
            // 忽略警告
            ignoreUnescapedHTML: true,
        });
        // 直接找到所有的 pre 标签
        const pres = dgHtmlDOM?.querySelectorAll("pre");
        if (pres && pres.length > 0) {
            pres.forEach((el) => {
                // 让每个 code 内容实现代码高亮
                highlight.highlightElement(el);
            });
        }
    }, [detail]);

    //导航栏中展示作者信息
    const wrapperRef = useRef<HTMLDivElement>(null);
    const authorRef = useRef<HTMLDivElement>(null);
    const [showNavAuthor, setShowNavAuthor] = useState(false);

    // 导航栏中展示作者信息
    useEffect(() => {
        if (loading) return;
        const wrapperDOM = wrapperRef.current!;
        // 创建一个节流函数
        const handleScroll = throttle(() => {
            const { bottom } = authorRef.current!.getBoundingClientRect();
            // 44 是 NavBar 的高度，因为 NavBar 会挡住页面内容，所以，此处需要减去它的高度
            if (bottom - 44 <= 0) {
                setShowNavAuthor(true);
            } else {
                setShowNavAuthor(false);
            }
        }, 200);
        wrapperDOM.addEventListener("scroll", handleScroll);
        return () => wrapperDOM.removeEventListener("scroll", handleScroll);
    }, [loading]);

    // 用于存储评论区域的元素对象
    const commentRef = useRef<HTMLDivElement | null>(null);
    //点击滚动到评论内容位置
    // 数量偏移量
    const [offset, setOffset] = useState<string | undefined>();
    // 是否还有更多数据可以加载
    const [hasMore, setHasMore] = useState(true);
    // 用于获取评论列表的方法
    // 拿到准备好的 comment 数据

    // 第一次：获取评论数据
    useEffect(() => {
        const commentData = async () => {
            if (art_id) {
                await dispatch(
                    getArticleComments(CommentType.Article, detail.art_id) as any
                );
            }
        };
        commentData();
    }, [dispatch, detail]);

    // 文章评论
    const { end_id, last_id } = comment;
    // 是否有更多评论
    const hasMoreComment = end_id !== last_id;
    // 以后每次：InfiniteScroll 加载评论数据
    const loadMoreComment = async () => {
        const lastCommentId = comment.results[comment.results.length - 1]?.com_id;
        if (art_id) {
            await dispatch(
                getMoreArticleComments(
                    CommentType.Article,
                    detail.art_id,
                    lastCommentId ? lastCommentId : null
                ) as any
            );
        }
    };
    // 对文章进行评论的回调函数
    const onSubmit = async () => {
        let res = await http.post<ArticleCommentResponse>("/comments", {
            target: art_id,
            content: TextAreavalue,
        });
        dispatch(getArticleComments(CommentType.Article, detail.art_id) as any);
        setVisible1(false);
    };

    // 点击评论滚动到评论区域
    const scrollToComments = () => {
        if (commentRef.current) {
            commentRef.current.scrollIntoView({ behavior: 'smooth' });
        }
    };

    // 点击评论按钮时调用滚动函数
    const handleCommentButtonClick = () => {
        scrollToComments();
    };
    return loading ? (
        <ContentLoader
            speed={2}
            width={375}
            height={230}
            viewBox="0 0 375 230"
            backgroundColor="#f3f3f3"
            foregroundColor="#ecebeb"
        >
            <rect x="16" y="8" rx="3" ry="3" width="340" height="10" />
            <rect x="16" y="26" rx="0" ry="0" width="70" height="6" />
            <rect x="96" y="26" rx="0" ry="0" width="50" height="6" />
            <rect x="156" y="26" rx="0" ry="0" width="50" height="6" />
            <circle cx="33" cy="69" r="17" />
            <rect x="60" y="65" rx="0" ry="0" width="45" height="6" />
            <rect x="304" y="65" rx="0" ry="0" width="52" height="6" />
            <rect x="16" y="114" rx="0" ry="0" width="340" height="15" />
            <rect x="263" y="208" rx="0" ry="0" width="94" height="19" />
            <rect x="16" y="141" rx="0" ry="0" width="340" height="15" />
            <rect x="16" y="166" rx="0" ry="0" width="340" height="15" />
        </ContentLoader>
    ) : (
        <>
            {/* 顶部固定部分 */}
            <div className={styles.header}>
                <Header
                    title={
                        showNavAuthor && (
                            <div className="nav-author">
                                <div className={styles.avatar}>
                                    <img
                                        src={detail?.aut_photo}
                                        alt=""
                                        style={{
                                            width: "20px",
                                            height: "20px",
                                            verticalAlign: "middle",
                                            marginRight: "20px",
                                            borderRadius: "20px",
                                        }}
                                    />
                                    <span style={{ fontSize: "13px" }}>{detail?.aut_name}</span>
                                </div>
                            </div>
                        )
                    }
                    left={<Back />}
                    right={<MoreOutline />}
                />
            </div>
            {/* 内容部分 */}
            <div className={styles.article} ref={wrapperRef}>
                <div className={styles.title}>{detail?.title}</div>
                <div className={styles.meta}>
                    <span>{dayjs(detail?.pubdate).locale("zh-cn").format("LL")}</span>
                    <span>{detail?.read_count} 阅读</span>
                    <span>{detail?.comm_count} 评论</span>
                </div>
                <div className={styles.author} ref={authorRef}>
                    <div className={styles.avatar}>
                        <img src={detail?.aut_photo} alt="" />
                        <span>{detail?.aut_name}</span>
                        <button
                            className={detail.is_followed ? styles.active : styles.button}
                            onClick={() => onFollow(detail.aut_id, detail.is_followed)}
                        >
                            {detail.is_followed ? "已关注" : "+关注"}
                        </button>
                    </div>
                </div>
                <div className={styles.content}>
                    <div
                        className="content-html dg-html"
                        dangerouslySetInnerHTML={{
                            __html: DOMPurify.sanitize(content),
                        }}
                    />
                </div>
                <div className={styles.footnote}>
                    文章发布于：{dayjs(detail?.pubdate).locale("zh-cn").format("LL")}
                </div>
                <div className={styles.comment} ref={commentRef}>
                    <h4 className={styles.title}>全部评论 ({detail?.comm_count})</h4>
                    {comment.length === 0 && (
                        <div className={styles.noReply}>
                            <img src={require("../../assets/images/none.png")} alt="" />
                            <span>还没有人评论哦</span>
                        </div>
                    )}
                    {comment.results.map((item: any) => (
                        <Comment key={comment.com_id} comment={item} art_id={art_id} />
                    ))}
                    <InfiniteScroll hasMore={hasMoreComment} loadMore={loadMoreComment} />
                </div>
            </div>

            <div className={styles.bar}>
                <div
                    className={styles.sofa}
                    onClick={() => {
                        setVisible1(true);
                    }}
                >
                    <FillinOutline className={styles.icon} />
                    <span>去评论</span>
                </div>
                <div className={styles.icons}>
                    <div className={styles.item} onClick={handleCommentButtonClick}>
                        <Icon type={"iconbtn_comment"} />
                        <span>评论</span>
                    </div>
                    <div
                        className={styles.item}
                        onClick={() => onLike(detail.art_id, detail.attitude)}
                    >
                        <Icon
                            type={
                                detail.attitude === 1 ? "iconbtn_like_sel" : "iconbtn_like2"
                            }
                        />
                        <span>点赞</span>
                    </div>
                    <div
                        className={styles.item}
                        onClick={() => onCollected(detail.art_id, detail.is_collected)}
                    >
                        <Icon
                            type={
                                detail.is_collected ? "iconbtn_collect_sel" : "iconbtn_collect"
                            }
                        />
                        <span>收藏</span>
                    </div>
                    <div className={styles.item}>
                        <Icon type={"iconbtn_share"} />
                        <span>分享</span>
                    </div>
                </div>
            </div>

            <Popup
                visible={visible1}
                onMaskClick={() => {
                    setVisible1(false);
                }}
                onClose={() => {
                    setVisible1(false);
                }}
                bodyStyle={{ height: "100vh" }}
            >
                <NavBar
                    onBack={() => {
                        setVisible1(false);
                    }}
                >
                    评论文章
                </NavBar>
                <TextArea
                    placeholder="说点什么~"
                    value={TextAreavalue}
                    onChange={(val) => {
                        setTextAreavalue(val);
                    }}
                />
                <Button size="mini" color="primary" onClick={onSubmit}>
                    发表
                </Button>
            </Popup>
        </>
    );
};
export default Article;
